from rest_framework import serializers
from django.contrib.auth import authenticate
from ..models import CustomUser, Institution, Laboratory

class InstitutionSerializer(serializers.ModelSerializer):
    """机构序列化器"""
    value = serializers.CharField(source='code', read_only=True)
    label = serializers.CharField(source='name', read_only=True)

    class Meta:
        model = Institution
        fields = ['value', 'label']


class LaboratorySerializer(serializers.ModelSerializer):
    """实验室序列化器"""
    value = serializers.CharField(source='code', read_only=True)
    label = serializers.CharField(source='name', read_only=True)
    institution_code = serializers.CharField(source='institution.code', read_only=True)

    class Meta:
        model = Laboratory
        fields = ['value', 'label', 'institution_code']


class UserSerializer(serializers.ModelSerializer):
    """用户序列化器"""
    institution_name = serializers.CharField(source='institution.name', read_only=True)
    laboratory_name = serializers.CharField(source='laboratory.name', read_only=True)
    institution = serializers.CharField(source='institution.code', read_only=True)
    laboratory = serializers.CharField(source='laboratory.code', read_only=True)

    class Meta:
        model = CustomUser
        fields = [
            'id', 'username', 'email', 'full_name', 'phone',
            'institution', 'institution_name', 'laboratory', 'laboratory_name',
            'user_type', 'date_joined', 'last_login'
        ]
        read_only_fields = ['id', 'date_joined', 'last_login']


class LoginSerializer(serializers.Serializer):
    """登录序列化器"""
    email = serializers.EmailField()
    password = serializers.CharField(write_only=True)
    user_type = serializers.ChoiceField(choices=[('member', '实验室成员'), ('laboratory', '实验室')], required=True, help_text="用户类型")

    def validate(self, attrs):
        email = attrs.get('email')
        password = attrs.get('password')
        user_type = attrs.get('user_type')

        if not all([email, password, user_type]):
            raise serializers.ValidationError('请提供完整的登录信息')

        # 验证邮箱和密码
        user = authenticate(username=email, password=password)
        if not user:
            raise serializers.ValidationError('邮箱不存在或密码错误')
        if not user.is_active:
            raise serializers.ValidationError('邮箱已被禁用')

        # 验证用户类型权限
        if user.user_type == 'laboratory' and user_type != 'laboratory':
            raise serializers.ValidationError('邮箱不存在或密码错误')
        
        if user.user_type == 'member' and user_type != 'member':
            raise serializers.ValidationError('邮箱不存在或密码错误')

        attrs['user'] = user
        attrs['institution'] = user.institution
        attrs['laboratory'] = user.laboratory
        return attrs